<template>
  <div
    class="progress-parent"
    v-show="store.progressVisible && !store.exhibitsInfoShow && !store.childRemarksShow"
    :class="{
      'progress-parent-wap': store.isMobileType,
    }"
  >
    <div class="progress-container" @mousedown="handleMouseDown" @touchstart="handleTouchStart">
      <div class="progress-bar" :style="{ width: progress + '%' }"></div>

      <div
        :class="{
          'progress-node-pc': !store.isMobileType,
        }"
        v-show="item.progressNum"
        v-for="(item, index) in nodesList"
        :key="index"
        class="progress-node"
        :style="{ left: item.progressNum ? item.progressNum + '%' : 0 + '%' }"
        @click.stop="jumpToNode(item)"
      >
        <div class="shadow2"></div>
        <div class="node-shadow">
          <div class="shadow">
            <img v-if="item.value" class="shadow-img" :src="urls + item.value + '?imageView2/3/format/webp'" alt="" />
            <nullImage v-else/>
            <div class="title-box">
              <span>{{ item.text }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import nullImage from '@/components/imageNull/index.vue';
import { publicUrls } from '@/utils/minxin';
import { urls } from '@/utils/request/upload';
import { psthOutline } from '@/hooks/menuHooks';
import { useProjectStore } from '@/store';
import { useRoute } from 'vue-router';
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue';
import { cloneDeep } from 'lodash';
const store = useProjectStore();
const route = useRoute();
const props = defineProps({
  scrollDom: {
    type: Object,
  },
  scrollLeftNum: {
    type: Number,
  },
});
const nodesList = ref([]);
const emit = defineEmits(['emitScroll']);
const progress = ref(0);
// 存储节点的位置信息，是一个数组，元素表示节点在进度条上的百分比位置
// const nodes = ref([25, 50, 75]);
// 标记是否正在拖动
const isDragging = ref(false);
// 拖动开始时的初始进度
const initialProgress = ref(0);
// 拖动开始时的鼠标或触摸起始位置
let startX = 0;
let startY = 0;

const handleMouseDown = (e) => {
  startX = e.clientX;
  isDragging.value = true;
  initialProgress.value = progress.value;
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};
const getNodesList = async () => {
  let arrInfo = cloneDeep(store.templateMOdeList);
  nodesList.value = arrInfo;

  // console.log(nodesList.value, '一级大纲列表');

  //   arr = [];
  if ((route.name == 'templateedit' || route.name == 'exhibitionHome') && store.progressVisible) {
    nodesList.value.forEach((el) => {
      el.progressNum = 0;
    });
    store.templateMOdeList.forEach((el) => {
      setTimeout(() => {
        getLeftDistance('Level1outline' + el.id, el.id);
      }, 10);
    });
  }

  // console.log(nodesList.value);
  // 'Level1outline'
};

onMounted(() => {
  setInterval(() => {
    if (store.progressVisible && !store.exhibitsInfoShow && !store.childRemarksShow) {
      getNodesList();
    } 
  }, 60000);
  // setTimeout(() => {
  //   getNodesList();
  // }, 300);
});
const getLeftDistance = async (byId: string, id: number) => {
  if(store.previewMode === 2){return}
  let distance = 0;
  let currentElement = document.getElementById(byId);
  let parent = currentElement.offsetParent;
  
  while (parent) {
    distance += currentElement.offsetLeft;
    currentElement = parent;
    parent = parent.offsetParent;
  }
  // console.log('元素距滚动元素最左侧的距离:', (distance * 100) / props.scrollDom.scrollWidth);
  nodesList.value.forEach((el) => {
    if (el.id === id && distance) {
      el.progressNum = Number(((distance * 100) / props.scrollDom.scrollWidth).toFixed(3));
    }
  });
};
const handleTouchStart = (e) => {
  let element: any = document.getElementById('app'); //需要全屏容器的id
  if (element.style.transform == 'rotate(90deg)') {
    startY = e.touches[0].clientY;
  }
  // e.preventDefault();
  startX = e.touches[0].clientX;
  isDragging.value = true;
  initialProgress.value = progress.value;
  document.addEventListener('touchmove', handleTouchMove, { passive: false });
  document.addEventListener('touchend', handleTouchEnd, { passive: false });
  // e.stopPropagation();
};

const handleMouseMove = (e) => {
  if (!isDragging.value) return;
  const dx = e.clientX - startX;
  const containerWidth = document.querySelector('.progress-container').offsetWidth;
  const newProgress = initialProgress.value + (dx / containerWidth) * 100;
  progress.value = Number(Math.max(0, Math.min(100, newProgress)).toFixed(3));
  //   console.log(progress.value)
  emit('emitScroll', (progress.value / 100) * (props.scrollDom.scrollWidth - props.scrollDom.clientWidth));
};

const handleTouchMove = (e) => {
  if (!isDragging.value) return;
  let element: any = document.getElementById('app'); //需要全屏容器的id
  e.preventDefault();
  if (element.style.transform == 'rotate(90deg)') {
    const dx = e.touches[0].clientY - startY;
    const containerWidth = document.querySelector('.progress-container').offsetWidth;
    console.log('44444', containerWidth);
    const newProgress = initialProgress.value + (dx / containerWidth) * 100;

    progress.value = Number(Math.max(0, Math.min(100, newProgress)).toFixed(3));
    //   console.log(progress.value)
    emit('emitScroll', (progress.value / 100) * (props.scrollDom.scrollWidth - props.scrollDom.clientWidth));
  } else {
    const dx = e.touches[0].clientX - startX;
    const containerWidth = document.querySelector('.progress-container').offsetWidth;
    const newProgress = initialProgress.value + (dx / containerWidth) * 100;
    progress.value = Number(Math.max(0, Math.min(100, newProgress)).toFixed(3));
    //   console.log(progress.value)
    emit('emitScroll', (progress.value / 100) * (props.scrollDom.scrollWidth - props.scrollDom.clientWidth));
  }
};

const handleMouseUp = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
};

const handleTouchEnd = () => {
  isDragging.value = false;
  document.removeEventListener('touchmove', handleTouchMove, { passive: false });
  document.removeEventListener('touchend', handleTouchEnd, { passive: false });
};

const jumpToNode = (item: any) => {
  progress.value = item.progressNum;
  emit('emitScroll', (progress.value / 100) * (props.scrollDom.scrollWidth - props.scrollDom.clientWidth));
  // setTimeout(() => {
  //   psthOutline('Level1outline' + item.id);
  // }, 200);
};
const upDateScroll = () => {
  //进度条更新方法、
  //  console.log(props.scrollLeftNum)
  //  console.log(props.scrollDom.scrollWidth)
  let getScrollwidth = props.scrollDom.scrollWidth - props.scrollDom.clientWidth;
  //  console.log(props.scrollLeftNum/props.scrollDom.scrollWidth*100)
  let percentage = (props.scrollLeftNum / getScrollwidth) * 100;
  percentage = Number(percentage.toFixed(3));
  //  console.log(percentage)
  progress.value = percentage;
};
watch(
  () => props.scrollLeftNum,
  () => {
    setTimeout(() => {
      upDateScroll();
    }, 0);
  },
  { deep: true },
);
watch(
  () => store.tabvalue,
  () => {
    setTimeout(() => {
      getNodesList();
    }, 0);
  },
  { deep: true },
);
watch(
  () => store.progressVisible,
  () => {
    setTimeout(() => {
      if (store.progressVisible) {
        getNodesList();
      }
    }, 0);
  },
  { deep: true },
);
onMounted(() => {
  // 可以在这里添加一些初始化逻辑
});

onBeforeUnmount(() => {
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
  document.removeEventListener('touchmove', handleTouchMove);
  document.removeEventListener('touchend', handleTouchEnd);
});
</script> 

<style scoped lang="less">
.progress-parent {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  bottom: 40px;
  left: 64px;
  width: calc(100% - 128px);
  height: 20px;
  z-index: 999;
  transform: scaleZ(1px);
}
.progress-container {
  cursor: pointer;
  position: relative;
  width: 100%;
  height: 8px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}
.progress-bar {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: #e62b17;
  border-radius: 4px;
}
/* .progress-nodes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 6;
} */
.progress-node {
  // display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ffffff;
  cursor: pointer;
  z-index: 6;
  transform: translateX(-4px);
  .node-shadow {
    position: absolute;
    top: -156px;
    left: calc(50% - 108px);

    width: 216px;
    height: 144px;
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    display: none;
  }
  .shadow {
    position: relative;
    display: flex;
    width: 216px;
    height: 144px;
    border-radius: 10px;
    overflow: hidden;
  }
  .shadow-img {
    width: 216px;
    height: 144px;
    object-fit: cover;
    border-radius: 10px;
  }
  .title-box {
    display: flex;
    position: absolute;
    padding: 8px 12px;
    padding-top: 18px;
    bottom: 0;
    left: 0;
    width: 216px;
    height: 50px;
    background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, #000000 100%);
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.3);
    border-radius: 0px 0px 8px 8px;
    z-index: 66;
    span {
      width: 192px;
      height: 24px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 16px;
      color: #ffffff;
      line-height: 24px;
      // text-shadow: 0px 0px 20px rgba(0, 0, 0, 0.3);
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.progress-node-pc:hover {
  .node-shadow {
    display: flex;
  }
}
.shadow2 {
  display: none;
}
.progress-parent-wap {
  height: 40px;
  .progress-container {
    height: 20px;
    border-radius: 10px;
  }
  .progress-container::before {
    content: '';
    width: 100%;
    height: 60px;
    position: absolute;
    top: -20px;
    left: 0px;
  }
  .progress-bar {
    border-radius: 10px;
  }
  .progress-node {
    width: 20px;
    height: 20px;
    transform: translateX(-10px);
  }
  .shadow2 {
    position: relative;
    display: flex;
    width: 100%;
    height: 100%;
  }
  .shadow2::before {
    position: absolute;
    top: 0;
    left: 0;
    content: '';
    width: 30px;
    height: 30px;
    transform: translateX(-5px) translateY(-5px);
  }
}
</style>